package net.e_agri.json;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.arnx.jsonic.JSON;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TopicConverter extends AbstractContentConverter implements ContentConverter {

	private static final Log log = LogFactory.getLog(TopicConverter.class);

	@Override
	public String parseSource(Source source, String url) {
		
		log.info("TopicConverter :" + url);

		//log.info(content);
		List<List<Object>> contentList = new ArrayList<List<Object>>();
		@SuppressWarnings("rawtypes")
		Map<String, List> contentMap = new LinkedHashMap<String, List>();
		List<Object> record = new ArrayList<Object>();
		List<String> imgs = new ArrayList<String>();

		if(url.indexOf("a=page_c_topic_detail") != -1
		|| url.indexOf("a=page_fh_diary&") != -1)
			contentMap.put("fields", Arrays.asList("title","remove_url","auther","date","body","images"));
		else
			contentMap.put("fields", Arrays.asList("title","auther","date","body","images"));
		Element dt = null;
		Element heading = null;
		String val = null;
		for(Element dl : source.getAllElements(HTMLElementName.DL)){

			record = new ArrayList<Object>();
			imgs = new ArrayList<String>();
			
			//title
			for(Element div : dl.getAllElements(HTMLElementName.DIV)){
				val = div.getTextExtractor().toString().replace("\n", "").replace("\r", "");
				if(div.getAttributeValue("class") == null){
					//record.add(val);
					continue;
				}else if("title".equals(div.getAttributeValue("class"))) {
					record.add(val.replace("削除", ""));

					//remove url
					if(url.indexOf("a=page_c_topic_detail") != -1
					|| url.indexOf("a=page_e_diary_detail") != -1
					|| url.indexOf("a=page_fh_diary&") != -1){
						int AtagCount = 0;
						for(Element a : div.getAllElements(HTMLElementName.A)){
							AtagCount++;
							if(a.getTextExtractor().toString().indexOf("削除") != -1){
								record.add(a.getAttributeValue("href"));
								break;
							}
						}
						if(record.size() == 1)
							record.add("N/A");
					}

					//Auther in replies
					heading = div.getFirstElement(HTMLElementName.P);
					if("heading".equals(heading.getAttributeValue("class"))){
						if(heading.getFirstElement(HTMLElementName.A) != null){
							//Topic Url in c_topic_list
							if(url.indexOf("a=page_c_home&") != -1
							|| url.indexOf("a=page_c_topic_list") != -1){
								record.add(heading.getFirstElement(HTMLElementName.A).getAttributeValue("href"));
							}else{
								record.add(heading.getFirstElement(HTMLElementName.A).getTextExtractor().toString());
							}
							break;
						}else{
							continue;
						}
					}
				}else if("footer".equals(div.getAttributeValue("class"))) {
					//url of dialy
					if(url.indexOf("a=page_f_home&") != -1
					|| url.indexOf("a=page_fh_diary_list") != -1
					|| url.indexOf("a=page_e_diary_list") != -1)
						record.add(div.getFirstElement(HTMLElementName.P)
										.getFirstElement(HTMLElementName.A).getAttributeValue("href"));

				}else if("name".equals(div.getAttributeValue("class"))) {
					//Auther of post
					record.add(val);
					break;
				}
			}
			if((url.indexOf("a=page_fh_diary&") != -1
			|| url.indexOf("a=page_e_diary_detail") != -1)
			&& record.size() <= 2){

				for(Element div : source.getAllElements(HTMLElementName.DIV)){
					if("partsHeading".equals(div.getAttributeValue("class"))) {
						//Auther of diary
						val = div.getTextExtractor().toString();
						if(val.contains("の日記") && !val.startsWith("最近の") && !val.startsWith("各月の")){
							record.add(val);
							break;
						}else if(val.contains("の投稿")){
							record.add(val);
							break;
						}
					}
				}
			}

			//date
			if((dt = dl.getFirstElement(HTMLElementName.DT)) != null){
				
				val = dt.getContent().toString()
					.replace("年", "/")
					.replace("月", "/")
					.replace("日", " ")
					.replace("<br />", "");
				
				if(val.lastIndexOf("<input type=") != -1)
					val = val.substring(0, val.lastIndexOf("<input type="));
				
				record.add(val);
			}

			//body
			val = "";
			for(Element p : dl.getAllElements(HTMLElementName.P)){
				if("text".equals(p.getAttributeValue("class"))){
					record.add(getBodyContent(p));
					break;
				}
			}
			if((url.indexOf("a=page_fh_diary&") != -1
			|| url.indexOf("a=page_e_diary_detail") != -1)
				&& record.size() <= 4){
				for(Element div : dl.getAllElements(HTMLElementName.DIV)){
					if("body".equals(div.getAttributeValue("class"))){

						record.add(getBodyContent(div));
						break;
					}
				}
			}

			//image
			String imageUrl = null;
			String cacheUrl = null;

			for(Element a : dl.getAllElements(HTMLElementName.A)){
				if(a.getAttributeValue("href") != null
				&& a.getAttributeValue("href").contains("img.php?filename=")){

					imageUrl = uriRoot + a.getAttributeValue("href").replace("&m=pc", "");
					cacheUrl = getImageCacheUrl(imageUrl);
					if(cacheUrl != null)
						imgs.add(cacheUrl);
					else
						imgs.add(imageUrl);
				}
			}
			record.add(imgs);

			log.debug("\t" + record.toString().replace(",", "\n\t\t"));
			contentList.add(record);
		}
		contentMap.put("data", contentList);

		return JSON.encode(contentMap);
	}

	private String getBodyContent(Element body){
		//TODO:replace <br /> to "\n" here
		//val = p.getTextExtractor().toString().replace("\n", "").replace("\r", "");

		String val = body.getContent().toString();
		String imageUrl = null;
		String cacheUrl = null;

		int pos = val.indexOf("<ul class=\"photo\">");
		if(pos != -1)
			val = val.substring(val.indexOf("</ul>") + "</ul>".length() + 1);

		val = val.replace("<img src=\"./", "<img src=\"" + uriRoot);
		
		final String imgTagSrc = "<img src=\"";
		pos = val.indexOf(imgTagSrc);
		while(pos != -1){
			pos = pos + imgTagSrc.length();
			imageUrl = val.substring(pos, val.indexOf("\"", pos+1));

			cacheUrl = getImageCacheUrl(imageUrl);
			if(cacheUrl != null)
				val.replace(imageUrl, cacheUrl);

			pos = val.indexOf(imgTagSrc,  pos+1);
		}
		
		return val;
	}
}
